from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import get_formatter_by_name
from pygments.styles import get_style_by_name

from pod.std import *
from html.util import tag, css


class CSS(Macro):
    name = "css"
    doctype = "html"
    
    def __init__(self, env, scope, *args, **kwargs):
        super(CSS, self).__init__()
        css(env, args[0], **kwargs)
        
    def __call__(self, content):
        pass

class Center(Macro):
    name = "center"
    doctype = "html"
    
    def __init__(self, ctx):
        super(Center, self).__init__()
    
    def __call__(self, content):
        #return "<center>%s</center>" % Macro.flatten(content)
        return tag("center")[Macro.flatten(content)]
        
class Bold(Macro):
    name = "b"
    doctype = "html"
    
    def __init__(self, ctx):
        super(Bold, self).__init__()
        
    def __call__(self, content):
        return tag("b")[Macro.flatten(content)]


class Italic(Macro):
    name = "i"
    doctype = "html"
    
    def __init__(self, ctx):
        super(Italic, self).__init__()
        
    def __call__(self, content):
        return tag("i")[Macro.flatten(content)]

class Paragraph(Macro):
    name = "p"
    doctype = "html"
    
    def __init__(self, ctx, **kwargs):
        super(Paragraph, self).__init__()
        self.attrs = kwargs
        
    def __call__(self, content):
        return tag("p", **self.attrs) [ Macro.flatten(content) ]
        
class Code(Macro):
    name="code"
    doctype = "html"
    
    counter = 0

    def __init__(self, ctx, language=None, output="html", style="friendly", escape=None):
        self.env = env
        self.language = language if language != None else env["default:language"]
        self.output = output
        self.style = style
        self.number = Code.counter
        self.escape = escape

        self.lexer = get_lexer_by_name(self.language)
        self.formatter = get_formatter_by_name(self.output, style=get_style_by_name(self.style))

        if Code.counter == 0:
            self.env["doc.preamble"].append('<style type="text/css">\n%s</style>\n' % self.formatter.get_style_defs(".highlight"))
        Code.counter += 1

    def __call__(self, content):
        content = Macro.flatten(content)
        if self.escape:
                content = content.replace("%s{" % self.escape, "{:")
                content = content.replace("%s}" % self.escape, ":}")
        #endif
        return "%s" % highlight(Macro.flatten(content), self.lexer, self.formatter)